/*
 * @Author: weidewei
 * @Date: 2025-11-19 15:39:51
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-21 16:16:50
 * @Description:
 * @FilePath: \2025-front-face\vite-react-ts-template\src\pages\useContext.tsx
 */
import React from 'react';
import styled from 'styled-components';

export default function useLayoutEffectComp() {
  /**
   * useLayoutEffect:用于在浏览器重新绘制屏幕之前触发
        * useLayoutEffect(() => {
        // 副作用代码
        return () => {
          // 清理代码
        }
      }, [dependencies]);
   */
  const [n, setN] = useState(0);
  // 阻塞DOM
  // useLayoutEffect(()=>{
  //   for(let i=0;i<30000;i++) {
  //     setN(i);
  //   }
  // },[]);
  // 不阻塞DOM
  // useEffect(()=>{
  //   for(let i=0;i<30000;i++) {
  //     setN(i);
  //   }
  // },[]);
  function handleScroll (e: React.UIEvent<HTMLUListElement>) {
    const scrollTop = e.currentTarget.scrollTop;
    window.history.replaceState(null, '', `?top=${scrollTop}`);
  }

  useLayoutEffect(() => {
    const top = window.location.search.split('=')[1];
    if (top) {
        const container = document.getElementById('list');
        container?.scrollTo(0, Number(top));
    }
}, []);

  return (
    <Wrapper>
      <div className="use-layout-effect">
        {/* root */}
        {/* {
      Array.from({ length: n }).map((_, index) => (
        <div key={index}>{index}</div>
      ))
      } */}
        <ul onScroll={handleScroll} id="list" style={{ height: '500px', overflowY: 'scroll' }}>
          {Array.from({ length: 500 }, (_, i) => (
            <li key={i}>Item {i + 1}</li>
          ))}
        </ul>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .use-layout-effect {
    color: #000;
  }

  #root1 {
    width: 200px;
    height: 200px;
    background: rgb(13, 238, 125);
  }

  #root2 {
    width: 200px;
    height: 200px;
    background: rgb(39, 39, 247);
    margin-top: 20px;
    position: absolute;
    top: 230px;
  }
`;
